package com.fankui.crowd.handler;

import com.fankui.crowd.api.MySQLRemoteService;
import com.fankui.crowd.config.OSSProperties;
import com.fankui.crowd.constant.CrowdConstant;
import com.fankui.crowd.entity.vo.*;
import com.fankui.crowd.util.CrowdUtil;
import com.fankui.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName ProjectConsumerHandler
 * Description TODO
 * Date 2023/8/14 22:58
 *
 * @Author 范奎
 * @Since JDK 11
 */
@Controller
public class ProjectConsumerHandler {
    @Autowired
    private OSSProperties ossProperties;
    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    @RequestMapping("/create/project/information.html")
    public String saveProjectBasicInfo(ProjectVO projectVO, MultipartFile headerPicture, List<MultipartFile> detailPictureList, HttpSession session, ModelMap modelMap) throws IOException {
        // 1 判断当前headerPicture对象是否为空
        if (headerPicture.isEmpty()) {
            // 如果没有上传头图则返回到表单页面并提示错误消息
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_EMPTY);
            return "project-launch";
        }
        // 2 如果当前headerPicture对象不为空，则执行上传
        ResultEntity<String> uploadHeaderPicResultEntity = CrowdUtil.uploadFileToOss(ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret(), ossProperties.getBucketName(), ossProperties.getBucketDomain(), ossProperties.getEndPoint(), headerPicture.getOriginalFilename(), headerPicture.getInputStream());
        String result = uploadHeaderPicResultEntity.getResult();
        // 3 判断头图是否上传成功
        if (ResultEntity.SUCCESS.equals(result)) {
            // 如果上传成功则获取图片访问路径并存入ProjectVO对象中
            String headerPicturePath = uploadHeaderPicResultEntity.getData();
            projectVO.setHeaderPicturePath(headerPicturePath);
        } else {
            // 如果上传失败则返回到表单页面并提示错误消息
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
            return "project-launch";
        }
        // 4 创建一个用来存放详情图片路径的集合
        List<String> detailPicturePathList = new ArrayList<>();
        // 5 检查detailPictureList是否有效
        if (detailPictureList == null || detailPictureList.size() == 0) {
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
            return "project-launch";
        }
        // 6 遍历detailPictureList
        for (MultipartFile detailPicture : detailPictureList) {
            // 判断当前detailPicture是否为空
            if (detailPicture.isEmpty()) {
                // 检测到详情图片中单个文件为空也返回到表单页面并提示错误消息
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
                return "project-launch";
            }
            // 执行上传
            ResultEntity<String> detailUploadResultEntity = CrowdUtil.uploadFileToOss(ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret(), ossProperties.getBucketName(), ossProperties.getBucketDomain(), ossProperties.getEndPoint(), detailPicture.getOriginalFilename(), detailPicture.getInputStream());
            // 检查上传结果
            String detailUploadResult = detailUploadResultEntity.getResult();
            if (ResultEntity.SUCCESS.equals(detailUploadResult)) {
                String detailPicturePath = detailUploadResultEntity.getData();
                // 收集上传的图片的访问路径
                detailPicturePathList.add(detailPicturePath);
            } else {
                // 如果上传失败则返回到表单页面并显示错误消息
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
                return "project-launch";
            }
        }
        // 7 将存放了详情图片访问路径的集合存入PrijectVO中
        projectVO.setDetailPicturePathList(detailPicturePathList);
        // 8 将projectVO对象存入Session域
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);
        // 9 重定向到下一个收集回报信息的页面
        return "redirect:http://101.132.226.28/project/return/info/page.html";
    }

    @ResponseBody
    @RequestMapping("/create/upload/return/picture.json")
    public ResultEntity<String> uploadReturnPicture(@RequestParam("returnPicture") MultipartFile returnPicture) throws IOException {
        return CrowdUtil.uploadFileToOss(ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret(), ossProperties.getBucketName(), ossProperties.getBucketDomain(), ossProperties.getEndPoint(), returnPicture.getOriginalFilename(), returnPicture.getInputStream());
    }

    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(ReturnVO returnVO, HttpSession session) {
        try {
            // 1 从session域中读取之前缓存的ProjectVO对象
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
            // 2 判断projectVO是否为null
            if (projectVO == null) {
                return ResultEntity.failed(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MESSING);
            }
            // 3 从projectVO对象中获取存储回报信息的集合
            List<ReturnVO> returnVOList = projectVO.getReturnVOList();
            // 4 判断returnVOList集合是否有效
            if (returnVOList == null || returnVOList.size() == 0) {
                // 5 创建集合对象对returnVOList进行初始化
                returnVOList = new ArrayList<>();
                // 6 将returnVOList集合设置到projectVO对象中
                projectVO.setReturnVOList(returnVOList);
            }
            // 7 将收集了表单数据的returnVO对象存入集合
            returnVOList.add(returnVO);
            // 8 把ProjectVO对象重新存入Session域中
            session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    @RequestMapping("/create/confirm.json")
    public String saveConfirm(MemberConfirmInfoVO memberConfirmInfoVO, HttpSession session, ModelMap modelMap) {
        // 1 从Session域中读取ProjectVO对象
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
        // 2 判断projectVO是否为null
        if (projectVO == null) {
            throw new RuntimeException(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MESSING);
        }
        // 3 将确认信息数据封装到projectVO对象中
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);
        // 4 从Session域读取当前登录的用户信息
        MemberLoginVO memberLoginVo = (MemberLoginVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        Integer memberId = memberLoginVo.getId();
        // 5 调用远程方法保存projectVO对象
        ResultEntity<String> saveResultEntity = mySQLRemoteService.saveProjectVORemote(projectVO, memberId);
        // 6 判断远程保存是否成功
        String result = saveResultEntity.getResult();
        if (ResultEntity.FAILED.equals(result)) {
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, saveResultEntity.getMessage());
            return "project-confirm";
        }
        // 7 将临时的ProjectVO对象从Session域中移除
        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
        // 8 如果远程保存成功则跳转到最终完成页面
        return "redirect:http://101.132.226.28/project/create/success.html";
    }

    @RequestMapping("/get/project/detail/{projectId}")
    public String getProjectDetail(@PathVariable("projectId") Integer projectId, Model model) {
        ResultEntity<DetailProjectVO> resultEntity = mySQLRemoteService.getDetailProjectVORemote(projectId);
        if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
            DetailProjectVO detailProjectVO = resultEntity.getData();
            model.addAttribute("detailProjectVO", detailProjectVO);
        }
        return "project-detail";
    }
}
